﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraEditors;
using DevExpress.XtraBars;
using System.Collections;
using DevExpress.XtraBars.Helpers;
using OilDB;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.Data.SqlClient;
using SyncLib;
using System.Net.Mail;
using DevExpress.XtraEditors.Repository;

namespace MainApp
{
    public partial class FrmMain : XtraForm
    {
        private DataServices data;
        private bool missClick;
        private Guid currentStore = Guid.Empty;

        IDbConnection mainConnection;
        public FrmMain()
        {
            InitializeComponent();
            barManager.ForceInitialize();
            SkinHelper.InitSkinPopupMenu(mPaintStyle);

        }

        private void mainFrm_Load(object sender, EventArgs e)
        {
            mainTabControl.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;
            LoadCurrentStore();
            if (Login())
            {
                SetGridDataSource();
                SetBindingSource();
                SetSomething();
                setDataSourceForReceiptNumber();
                setDataSourceForReceiptCompany();

                cashReport.Data = data;
                cashReport.updateProducts();
                cashReport.updateStores();
                inReport.setReportType(InOutReport.InOutReportType.InType);
                inReport.Data = data;
                inReport.updateStores();
                //InReport.updateProducts();

                outReport.setReportType(InOutReport.InOutReportType.OutType);
                outReport.Data = data;
                outReport.updateStores();
                //OutReport.updateProducts();

                receiptReport.setReportType(InOutReport.InOutReportType.ReceiptType);
                receiptReport.Data = data;
                receiptReport.updateStores();
                //receiptReport.updateProducts();

                dockNavigator.Visibility = Properties.Settings.Default.dockNavigatorVisibility;
                dockNavigator_VisibilityChanged(dockNavigator, null);
                btnInputSell.Enabled = mainTabControl.SelectedTabPage == tabSells;
                btnPayAll.Enabled = mainTabControl.SelectedTabPage == tabDebtStatistics;

                ((BarButtonItem)mainMenubar.Items[mainTabControl.SelectedTabPage.Name.Replace("tab", "btn")]).Down = true;

                btnSave.Enabled = false;
                btnUndo.Enabled = false;

                SetRowUpdatedEvent();
                if (currentStore != Guid.Empty)
                    InitControlProperties();
            }
            DevExpress.XtraNavBar.NavBarItem item = navBarControl.Items[mainTabControl.SelectedTabPage.Name.Replace("tab", "item")];
            if (item != null)
            {
                item.Appearance.Options.UseForeColor = true;
                item.Appearance.Options.UseFont = true;
            }

            gridViewDebts.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gridViewDebts_CellValueChanged);

            mainTabControl.SelectedPageChanging += new DevExpress.XtraTab.TabPageChangingEventHandler(mainTabControl_SelectedPageChanging);
            InitTabSells();
            dataSetOilManagement.Stores.AddStoresRow(Guid.Empty, "Tất cả", "", "");
            foreach (DataSetOilManagement.StoresRow row in data.DsOil.Stores)
            {
                dataSetOilManagement.Stores.Rows.Add(row.ItemArray);
            }

            DebtStoreEdit.EditValue = currentStore;
            DebtComStoreEdit.EditValue = currentStore;
            if (currentStore != Guid.Empty)
            {
                DebtStoreEdit.Enabled = false;
                DebtComStoreEdit.Enabled = false;
            }
            
        }

        #region InitNewRow
        private void gridView_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            DataRow row = view.GetDataRow(e.RowHandle);

            row["ID"] = Guid.NewGuid();
            try
            {
                row["ImportTime"] = DateTime.Now;
            }
            catch (Exception)
            {
                //throw;
            }
            try
            {
                row["ExpenseTime"] = DateTime.Now;
            }
            catch (Exception)
            {
                //throw;
            }
            try
            {
                row["ReceiptTime"] = DateTime.Now;
            }
            catch (Exception)
            {
                //throw;
            }
            try
            {
                row["PayTime"] = DateTime.Now;
            }
            catch (Exception)
            {
                //throw;
            }
            try
            {
                row["DebtTime"] = DateTime.Now;
            }
            catch (Exception)
            {
                //throw;
            }
            if (currentStore != Guid.Empty)
            {
                try
                {
                    row["StoreID"] = currentStore;
                }
                catch (Exception)
                {
                    //throw;
                }
                try
                {
                    if (view == gridViewCustomers || view == gridViewCompanies)
                    {
                        row["Note"] = data.CurrentStoreName;
                    }
                }
                catch (Exception)
                {
                    //throw;
                }
            }
        }
        #endregion

        private void gridView_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            //data.Commit();
            btnSave.Enabled = true;
            btnUndo.Enabled = true;
        }

        #region Validate_gridImports
        private void gridViewImports_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreID"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn cây xăng");
            }
            column = view.Columns["Product"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn loại sản phẩm");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số lượng");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
            if (e.Valid)
            {
                try //error when no data is proposed
                {
                    DataRowState tmp = DataRowState.Modified;
                    if (view.IsNewItemRow(e.RowHandle))
                        tmp = DataRowState.Added;
                    if (!data.ValidateAndUpdate_Imports(tmp, view.GetDataRow(e.RowHandle)))
                    {
                        e.Valid = false;
                        e.ErrorText = "Thay đổi sẽ làm lượng hàng nhập của sản phẩm nhỏ hơn lượng hàng bán";
                    }
                }
                catch (Exception)
                {

                    //throw;
                }
            }
        }
        #endregion

        #region Validate_gridSells
        private void gridViewSells_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            DataRow row = view.GetDataRow(e.RowHandle);

            try
            {//error when no data is proposed
                if (!data.ValidateAndUpdate_Sells(DataRowState.Modified, row))
                {
                    e.Valid = false;
                    e.ErrorText = "Thay đổi sẽ làm lượng hàng bán của sản phẩm lớn hơn lượng hàng nhập";
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }
        #endregion

        #region Validate_gridPayments
        private void gridViewPayments_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreID"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn cây xăng");
            }
            column = view.Columns["Customer"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn khách hàng");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số tiền");
            }

            if (e.Valid)
            {
                DataRow row = view.GetDataRow(e.RowHandle);
                Guid customer = (Guid)row["Customer"];
                decimal amount = (decimal)row["Amount"];
                if (!view.IsNewItemRow(e.RowHandle))
                {
                    Guid oldcustomer = (Guid)row["Customer", DataRowVersion.Current];
                    decimal oldamount = (decimal)row["Amount", DataRowVersion.Current];
                    if (oldcustomer == customer)
                    {
                        amount -= oldamount;
                    }
                }
                DataSetOilManagement.DebtStatistics_AllRow debtRow = data.DsOil.DebtStatistics_All.FindByCustomer(customer);
                if ((amount > 0) && (debtRow == null || debtRow.Debt < amount))
                {
                    e.Valid = false;
                    e.ErrorText = "Trả nợ vượt quá số nợ hiện tại";
                }
            }
            else
            {
                e.ErrorText = "Dữ liệu nhập có lỗi";
            }
            if (e.Valid)
            {
                try
                {
                    DataRowState tmp = DataRowState.Modified;
                    if (view.IsNewItemRow(e.RowHandle))
                        tmp = DataRowState.Added;
                    data.Update_Payments(tmp, view.GetDataRow(e.RowHandle));
                }
                catch (Exception)
                {

                    //throw;
                }
            }
        }
        #endregion

        #region Validate_gridDebts
        private void gridViewDebts_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreID"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn cây xăng");
            }
            column = view.Columns["Customer"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn khách hàng");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số lượng");
            }
            if (e.Valid)
            {
                if (!view.IsNewItemRow(e.RowHandle))
                {
                    DataRow row = view.GetDataRow(e.RowHandle);
                    Guid customer = (Guid)row["Customer"];
                    decimal amount = (decimal)row["Amount"];
                    Guid oldcustomer = (Guid)row["Customer", DataRowVersion.Current];
                    decimal oldamount = (decimal)row["Amount", DataRowVersion.Current];
                    if (oldcustomer == customer)
                    {
                        oldamount -= amount;
                    }
                    DataSetOilManagement.DebtStatistics_AllRow debtRow = data.DsOil.DebtStatistics_All.FindByCustomer(oldcustomer);
                    if ((oldamount > 0) && (debtRow == null || debtRow.Debt < oldamount))
                    {
                        e.Valid = false;
                        e.ErrorText = "Trả nợ vượt quá số nợ hiện tại";
                    }
                }
            }
            else
            {
                e.ErrorText = "Dữ liệu nhập có lỗi";
            }
            if (e.Valid)
            {
                try //error when no data is proposed
                {
                    DataRowState tmp = DataRowState.Modified;
                    if (view.IsNewItemRow(e.RowHandle))
                        tmp = DataRowState.Added;
                    data.Update_Debts(tmp, view.GetDataRow(e.RowHandle));
                }
                catch (Exception)
                {

                    //throw;
                }
            }
        }

        void gridViewDebts_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.IsNewItemRow(e.RowHandle) && e.Column.FieldName == "Customer")
            {
                OilDB.DataSetOilManagement.DebtsRow newRow = (OilDB.DataSetOilManagement.DebtsRow)view.GetDataRow(e.RowHandle);
                OilDB.DataSetOilManagement.CustomersRow row = data.DsOil.Customers.FindByID((Guid)newRow["Customer"]);
                if (!(row["Company"] is System.DBNull))
                {
                    newRow["Company"] = row["Company"];
                }
            }
            gridView_CellValueChanged(sender, e);
        }
        #endregion

        #region Validate_simpleGrids

        private void gridViewExpenses_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreID"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn cây xăng");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số tiền");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }


        private void gridViewCompanies_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["CompanyName"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập tên công ty");
            }
            else if (((string)view.GetRowCellValue(e.RowHandle, column)).Trim().Length == 0)
            {
                e.Valid = false;
                view.SetColumnError(column, "Tên công ty không thể để trống");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }

        private void gridViewCustomers_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["CustomerName"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập tên khách hàng");
            }
            else
            {
                String name = ((string)view.GetRowCellValue(e.RowHandle, column)).Trim();

                if (name.Length == 0)
                {
                    e.Valid = false;
                    view.SetColumnError(column, "Tên khách hàng không thể để trống");
                }
                else
                {
                    DataRow currRow = view.GetDataRow(e.RowHandle);
                    Guid company = (Guid)currRow["Company"];
                    Guid id = (Guid)currRow["Id"];
                    DataRow[] duplicate = data.DsOil.Customers.Select(String.Format("CustomerName = '{0}' AND Company = '{1}' AND ID <> '{2}'", name, company, id));
                    if (duplicate.Length > 0)
                    {
                        e.Valid = false;
                        view.SetColumnError(column, "Tên không thể trùng nhau");
                    }
                }
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }

        private void gridViewStores_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreName"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập tên cây xăng");
            }
            else if (((string)view.GetRowCellValue(e.RowHandle, column)).Trim().Length == 0)
            {
                e.Valid = false;
                view.SetColumnError(column, "Tên cây xăng không thể để trống");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }

        private void gridViewProducts_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            //only check when data is edited
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["ProductName"];
            if (((string)view.GetRowCellValue(e.RowHandle, column)).Trim().Length == 0)
            {
                e.Valid = false;
                view.SetColumnError(column, "Tên sản phẩm không thể để trống");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }

        private void gridViewReceipts_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.ClearColumnErrors();
            GridColumn column = view.Columns["StoreID"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn cây xăng");
            }
            column = view.Columns["ReceiptNumber"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số hóa đơn");
            }
            column = view.Columns["Company"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập khách hàng");
            }
            column = view.Columns["Product"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập loại xăng");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số lượng");
            }
            e.ErrorText = "Dữ liệu nhập có lỗi";
        }
        #endregion


        private void gridView_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (missClick)
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                return;
            }

            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;

            if (XtraMessageBox.Show(e.ErrorText + "\nBạn có muốn sửa lại không?\n Bấm Yes để sửa lại.\n Bấm No để bỏ qua.", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No)
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                GridView view = sender as GridView;
                view.CancelUpdateCurrentRow();
            }
        }
        #region PressKey_Delete
        private void gridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                GridView view = sender as GridView;
                if (view.FocusedRowHandle < 0)
                    return;

                if (XtraMessageBox.Show("Xóa những dòng đang chọn ?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;

                int[] index = view.GetSelectedRows();
                DataRow[] rows = new DataRow[index.Length];
                for (int i = 0; i < index.Length; i++)
                {
                    rows[i] = view.GetDataRow(index[i]);
                }

                bool check = true;
                string errorText = "\n Vui lòng kiểm tra lại";
                switch (view.GetViewCaption())
                {
                    case "Imports":
                        if (!(data.ValidateAndUpdate_Imports(DataRowState.Deleted, rows)))
                        {
                            //XtraMessageBox.Show("Việc xóa sẽ làm lượng hàng nhập của một số sản phẩm nhỏ hơn lượng hàng bán.\n Vui lòng kiểm tra lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            errorText = "Việc xóa sẽ làm lượng hàng nhập của một số sản phẩm nhỏ hơn lượng hàng bán.";
                            check = false;
                        }
                        break;
                    case "Sells":
                        data.ValidateAndUpdate_Sells(DataRowState.Deleted, rows);
                        break;
                    case "Payments":
                        data.Update_Payments(DataRowState.Deleted, rows);
                        break;
                    case "Debts":
                        if (!data.Validate_Delete_Debts(rows))
                        {
                            errorText = "Việc xóa sẽ làm dư nợ âm.";
                            check = false;
                        }
                        else
                        {
                            data.Update_Debts(DataRowState.Deleted, rows);
                        }
                        break;
                    case "Companies":
                        foreach (OilDB.DataSetOilManagement.CompaniesRow row in rows)
                        {
                            DataRow[] tmp = data.DsOil.Customers.Select(String.Format("Company = '{0}'", row.ID));
                            if (tmp.Length != 0)
                            {
                                check = false;
                                errorText = "Không thể xóa vì còn dữ liệu liên quan tới dữ liệu xe";
                                break;
                            }
                        }
                        break;
                    case "Customers":
                        foreach (OilDB.DataSetOilManagement.CustomersRow row in rows)
                        {
                            if (data.DsOil.Payments.Select(String.Format("Customer = '{0}'", row.ID)).Length != 0)
                            {
                                check = false;
                                errorText = "Không thể xóa vì còn dữ liệu liên quan tới dữ liệu thu nợ";
                                break;
                            }
                            else if (data.DsOil.Debts.Select(String.Format("Customer = '{0}'", row.ID)).Length != 0)
                            {
                                check = false;
                                errorText = "Không thể xóa vì còn dữ liệu liên quan tới dữ liệu nợ";
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }

                if (check)
                {
                    view.DeleteSelectedRows();
                    btnSave.Enabled = true;
                    btnUndo.Enabled = true;
                }
                else
                {
                    XtraMessageBox.Show(errorText, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }
        #endregion

        private void gridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            GridView view = sender as GridView;
            if (view.IsNewItemRow(e.FocusedRowHandle))
            {
                missClick = true;
                view.AddNewRow();
            }
        }



        private void gridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            missClick = false;
            GridView view = sender as GridView;
          
            

            if (view.Name == "gridViewReceipts")
            {
                //UpdateSource oF Receipt Number
                setDataSourceForReceiptNumber();     
                if (e.Column.FieldName == "Product")
                {
                    OilDB.DataSetOilManagement.ProductsRow prow = data.DsOil.Products.FindByID((Guid)e.Value);
                    if (prow != null)
                    {
                        DataRow row = view.GetDataRow(e.RowHandle);
                        row["Price"] = prow["Price"];
                        row["FeePerUnit"] = prow["Fee"];
                    }
                }
                else if (e.Column.FieldName == "Company")
                {
                    Guid companyId = findReceiptIdByName(e.Value.ToString());
                    if (!companyId.Equals(Guid.Empty))
                    {
                        OilDB.DataSetOilManagement.ReceiptsRow rrow = data.DsOil.Receipts.FindByID(companyId);
                        if (rrow != null)
                        {
                            DataRow row2 = view.GetDataRow(e.RowHandle);
                            row2["CompanyAddress"] = rrow["CompanyAddress"];
                            row2["TaxCode"] = rrow["TaxCode"];
                        }
                    }
                }
            }
            
        }
        private void setDataSourceForReceiptCompany()
        {
            try
            {
                if (ReceiptCompanySuggest.Items.Count > 0)
                {
                    ReceiptCompanySuggest.Items.Clear();
                }
                if (data.DsOil.Receipts != null)
                {
                    for (int i = 0; i < data.DsOil.Receipts.Rows.Count; i++)
                    {
                        ReceiptCompanySuggest.Items.Add(data.DsOil.Receipts.Rows[i]["Company"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Tải dữ liệu gợi ý cho Hóa đơn công ty lỗi");
            }
            
        }
        private void setDataSourceForReceiptNumber()
        {
            try
            {
                int MaxValue = 0;
                ReceiptNumber.Items.Clear();
                for (int i = 0; i < data.DsOil.Receipts.Rows.Count; i++)
                {
                    String receiptNumber = data.DsOil.Receipts.Rows[i]["ReceiptNumber"].ToString();
                    int tempCheck = 0;
                    if (Int32.TryParse(receiptNumber, out tempCheck))
                    {
                        int curValue = Convert.ToInt32(receiptNumber);
                        if (curValue > MaxValue)
                        {
                            MaxValue = curValue;
                        }
                    }
                    
                }
                for (int i = 0; i < 5; i++)
                {
                    ReceiptNumber.Items.Add(MaxValue + 5 - i);
                }

            }
            catch (Exception ex)
            {
                
            }
                        
        }
        private Guid findReceiptIdByName(String Rname)
        {
            for (int i = 0; i < data.DsOil.Receipts.Rows.Count; i++)
            {
                if (Rname.Equals(data.DsOil.Receipts.Rows[i]["Company"].ToString()))
                {
                    return (Guid)data.DsOil.Receipts.Rows[i]["ID"];
                }
            }
            return Guid.Empty;
        }

        private void CommonItemClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {

            DevExpress.XtraNavBar.NavBarItem item = sender as DevExpress.XtraNavBar.NavBarItem;
            //item.Appearance.Options.UseFont = true;
            //item.AppearanceHotTracked.Options.UseFont = true;

            string tabName = item.Name.Replace("item", "tab");
            foreach (DevExpress.XtraTab.XtraTabPage tab in mainTabControl.TabPages)
            {
                if (tab.Name == tabName)
                {
                    mainTabControl.SelectedTabPage = tab;
                    break;
                }
            }
        }

        void mainTabControl_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (e.PrevPage.Name == "tabSells")
            {
                if (btnSave.Enabled)
                {
                    if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu trước khi rời trang hoặc dữ liệu trở về ban đầu", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                        btnSave_ItemClick(null, null);
                    else
                    {
                        data.DsOil.RejectChanges();
                        btnUndo.Enabled = false;
                        btnSave.Enabled = false;
                    }
                }
            }
            if (e.Page.Name == "tabSells")
            {
                if (btnSave.Enabled)
                {
                    if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu trước khi vào trang", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                        btnSave_ItemClick(null, null);
                    else
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void mainTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            
            btnInputSell.Enabled = (e.Page == tabSells && currentStore != Guid.Empty);
            btnPayAll.Enabled = (e.Page == tabDebtStatistics && currentStore != Guid.Empty);
            DevExpress.XtraNavBar.NavBarItem item = navBarControl.Items[e.PrevPage.Name.Replace("tab", "item")];
            if (item != null)
            {
                item.Appearance.Options.UseFont = false;
                item.Appearance.Options.UseForeColor = false;
                item.AppearanceHotTracked.Options.UseFont = false;
            }

            item = navBarControl.Items[e.Page.Name.Replace("tab", "item")];
            if (item != null)
            {
                item.Appearance.Options.UseFont = true;
                item.Appearance.Options.UseForeColor = true;
                item.AppearanceHotTracked.Options.UseFont = true;
            }

            BarButtonItem btn = mainMenubar.Items[e.Page.Name.Replace("tab", "btn")] as BarButtonItem;
            if (btn != null)
            {
                btn.Down = true;
            }
            btn = mainMenubar.Items[e.PrevPage.Name.Replace("tab", "btn")] as BarButtonItem;
            if (btn != null)
            {
                btn.Down = false;
            }

            string tabName = e.Page.Name;
            if (tabName == "tabInStatistics" || tabName == "tabOutStatistics" || tabName == "tabCash" || tabName == "tabReceiptStatistics")
                if (btnSave.Enabled)
                {
                    if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu để có báo cáo chính xác nhất", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                        btnSave_ItemClick(null, null);
                }
        }

        private void dockNavigator_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            btnShowNavigator.Down = dockNavigator.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible;
            Properties.Settings.Default.dockNavigatorVisibility = dockNavigator.Visibility;
        }

        private void btnShowNavigator_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (dockNavigator.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Visible)
            {
                dockNavigator.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
                Properties.Settings.Default.dockNavigatorVisibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            }
            else
            {
                dockNavigator.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                Properties.Settings.Default.dockNavigatorVisibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
            }
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Properties.Settings.Default.Save();
        }

        private void CommonBtnChanged(object sender, ItemClickEventArgs e)
        {
            DevExpress.XtraBars.BarButtonItem item = e.Item as DevExpress.XtraBars.BarButtonItem;
            if (item == null)
            {
                return;
            }

            string tabName = item.Name.Replace("btn", "tab");
            foreach (DevExpress.XtraTab.XtraTabPage tab in mainTabControl.TabPages)
            {
                if (tab.Name == tabName)
                {
                    mainTabControl.SelectedTabPage = tab;
                    break;
                }
            }
        }

        private void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (data.Commit())
            {
                btnSave.Enabled = false;
                btnUndo.Enabled = false;
                data.UpdateStatistics(currentStore);
                inReport.UpdateReport();
                outReport.UpdateReport();
                receiptReport.UpdateReport();
                cashReport.updateReport();
                setDataSourceForReceiptCompany();
                setDataSourceForReceiptNumber();
            }
        }

        private void btnInputSell_ItemClick(object sender, ItemClickEventArgs e)
        {

            //int old = data.DsOil.Sells.Rows.Count;
            //int old2 = data.DsOil.Dispensers.Rows.Count;
            using (FrmInputSells_New tmp = new FrmInputSells_New(data, currentStore))
            {

                //tmp.ShowDialog();
                //if (old != data.DsOil.Sells.Rows.Count || old2 != data.DsOil.Dispensers.Rows.Count)
                if (tmp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    data.DsOil.ExportStatisticsAll.AcceptChanges();
                    btnSave.Enabled = true;
                    btnUndo.Enabled = true;
                }
            }
        }

        private void btnPayAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (PayDebts())
            {
                btnSave.Enabled = true;
                btnUndo.Enabled = true;
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnSave.Enabled == true)
            {
                if (DevExpress.XtraEditors.XtraMessageBox.Show("Lưu dữ liệu hiện tại?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    data.Commit();
                }
            }
        }

        private void btnPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (mainTabControl.SelectedTabPage.Name.Replace("tab", ""))
            {
                case "Products":
                    gridProducts.ShowPrintPreview();
                    break;
                case "Stores":
                    gridStores.ShowPrintPreview();
                    break;
                case "Companies":
                    gridCompanies.ShowPrintPreview();
                    break;
                case "Customers":
                    gridCustomers.ShowPrintPreview();
                    break;
                case "Imports":
                    gridImports.ShowPrintPreview();
                    break;
                case "Sells":
                    //gridSells.ShowPrintPreview();
                    break;
                case "Expenses":
                    gridExpenses.ShowPrintPreview();
                    break;
                case "Payments":
                    gridPayments.ShowPrintPreview();
                    break;
                case "Cash":
                    cashReport.showPrintPreView();
                    break;
                case "Debts":
                    gridDebts.ShowPrintPreview();
                    break;
                case "DebtStatistics":
                    gridDebtStatistics.ShowPrintPreview();
                    break;
                case "DebtStatisticsCompany":
                    gridDebtStatisticsCompany.ShowPrintPreview();
                    break;
                case "InStatistics":
                    inReport.printPreView();
                    break;
                case "OutStatistics":
                    outReport.printPreView();
                    break;
                case "ReceiptStatistics":
                    receiptReport.printPreView();
                    break;
                case "Receipts":
 	                gridReceipts.ShowPrintPreview();
 	                break;
                default:
                    break;
            }
        }


        private void BackupDatabase()
        {
            //Asking for the location and file name
            dlgSave.Filter = "Backup files|*.bak";
            if (dlgSave.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            //Excute BACKUP DATABASE command
            SqlConnectionStringBuilder CStr = new SqlConnectionStringBuilder(mainConnection.ConnectionString);
            string DBName = CStr.InitialCatalog;
            IDbCommand cmd = mainConnection.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "BACKUP DATABASE " + DBName + " TO DISK = @fileName WITH FORMAT";
            IDbDataParameter param = cmd.CreateParameter();
            param.DbType = DbType.String;
            param.ParameterName = "@fileName";
            param.Value = dlgSave.FileName;
            cmd.Parameters.Add(param);

            try
            {
                mainConnection.Open();
                cmd.ExecuteNonQuery();
                XtraMessageBox.Show("Cơ sở dữ liệu đã được lưu vào file " + dlgSave.FileName + " thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                XtraMessageBox.Show("Việc sao lưu cơ sở dữ liệu thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            mainConnection.Close();
        }

        private void ChangePassword(String OldPassword, String NewPassword)
        {
            try
            {
                mainConnection.Open();
                IDbCommand cmd = mainConnection.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                IDbDataParameter p = cmd.CreateParameter();
                p.ParameterName = "OldPassWord";
                p.Value = OldPassword;
                cmd.Parameters.Add(p);

                p = cmd.CreateParameter();
                p.ParameterName = "NewPassWord";
                p.Value = NewPassword;
                cmd.Parameters.Add(p);

                cmd.CommandText = "ChangePassword";

                cmd.ExecuteNonQuery();
                XtraMessageBox.Show("Mật khẩu đã được đổi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                XtraMessageBox.Show("Việc đổi mật khẩu thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                mainConnection.Close();
            }
        }

        private void AddUser(String UserName, String PassWord, int SysAdmin = 0)
        {
            try
            {
                mainConnection.Open();
                IDbCommand cmd = mainConnection.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                IDbDataParameter p = cmd.CreateParameter();
                p.ParameterName = "UserName";
                p.Value = UserName;
                cmd.Parameters.Add(p);

                p = cmd.CreateParameter();
                p.ParameterName = "PassWord";
                p.Value = PassWord;
                cmd.Parameters.Add(p);

                p = cmd.CreateParameter();
                p.ParameterName = "SysAdmin";
                p.Value = SysAdmin;
                cmd.Parameters.Add(p);

                cmd.CommandText = "AddUser";

                cmd.ExecuteNonQuery();
                XtraMessageBox.Show(String.Format("Đã thêm thành công người dùng {0}", UserName), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                XtraMessageBox.Show("Việc thêm người dùng thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                mainConnection.Close();
            }
        }

        private void RemoveUser(String UserName)
        {
            try
            {
                mainConnection.Open();
                IDbCommand cmd = mainConnection.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                IDbDataParameter p = cmd.CreateParameter();
                p.ParameterName = "UserName";
                p.Value = UserName;
                cmd.Parameters.Add(p);

                cmd.CommandText = "RemoveUser";

                cmd.ExecuteNonQuery();
                XtraMessageBox.Show(String.Format("Đã xóa thành công người dùng {0}", UserName), "Remove User", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                XtraMessageBox.Show("Việc xóa người dùng thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                mainConnection.Close();
            }
        }

        private void btnBackupDatabase_ItemClick(object sender, ItemClickEventArgs e)
        {
            BackupDatabase();
        }

        private void btnChangePassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            ChangePassDlg frm = new ChangePassDlg();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ChangePassword(frm.OldPassword, frm.NewPassword);
            }
        }

        private void btnNewAccount_ItemClick(object sender, ItemClickEventArgs e)
        {
            NewUserDialog frm = new NewUserDialog();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                switch (frm.AccountType)
                {
                    case "ReadOnly Account":
                        AddUser(frm.UserName, frm.Password, 0);
                        break;
                    case "Normal Account":
                        AddUser(frm.UserName, frm.Password, 1);
                        break;
                    case "Admin Account":
                        AddUser(frm.UserName, frm.Password, 2);
                        break;
                    default:
                        break;
                }
            }
        }

        private void popUser_Popup(object sender, EventArgs e)
        {
            data.GetUserListAdapter.Fill(data.DsOil.GetUserList);

            lvUsers.Clear();

            foreach (OilDB.DataSetOilManagement.GetUserListRow row in data.DsOil.GetUserList)
            {
                lvUsers.Items.Add(row.MemberName, row.MemberName, 0);
            }
        }

        private void btnUndo_ItemClick(object sender, ItemClickEventArgs e)
        {
            DoUndo();
        }

        private void btnImportReport_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (btnSave.Enabled)
            {
                if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu trước khi nhập báo cáo mới", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    btnSave_ItemClick(null, null);
            }
            ImportFromSyncFile();
            inReport.updateProducts();
            outReport.updateProducts();
            receiptReport.updateProducts();
            cashReport.updateProducts();
            DebtStoreEdit.EditValue = currentStore;
        }

        private void ImportFromSyncFile()
        {
            SyncPointManager sync = new SyncPointManager(mainConnection, currentStore);

            dlgOpen.Filter = "Sync Files|*.syn";
            if (dlgOpen.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            using (FrmImportPreview frm = new FrmImportPreview())
            {
                try
                {
                    sync.LoadData(dlgOpen.FileName);
                    bool OK;
                    try
                    {
                        OK = (currentStore != Guid.Empty) || (frm.showPreView(data.DsOil, sync.getDataSet(), (Guid)sync.getProperty("StoreID")));
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        OK = true;
                    }
                    if (OK)
                    {
                        sync.ImportSyncFile();
                        data.loadData(currentStore);
                        XtraMessageBox.Show(String.Format("File báo cáo {0} đã được nhập vào thành công.", dlgSave.FileName), "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    frm.Close();
                    cashReport.updateReport();
                    inReport.UpdateReport();
                    outReport.UpdateReport();
                    receiptReport.UpdateReport();
                }
            }
        }

        private void btnMakeReport_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (btnSave.Enabled)
            {
                if (XtraMessageBox.Show("Dữ liệu có thay đổi. Lưu dữ liệu để có báo cáo chính xác nhất", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                    btnSave_ItemClick(null, null);
            }
            createSyncFile();
        }

        private void createSyncFile()
        {
            FrmGetDate tmp = new FrmGetDate();
            DateTime date;
            if (tmp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                date = tmp.GetDate();
            }
            else
            {
                XtraMessageBox.Show("Hủy tác vụ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SyncPointManager sync = new SyncPointManager(mainConnection, currentStore);

            dlgSave.Filter = "Sync Files|*.syn";
            if (dlgSave.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            try
            {
                if (currentStore == Guid.Empty) //Server
                {
                    sync.CreateSyncFile(dlgSave.FileName, date, new string[] { "Products" });
                }
                else //Client
                {
                    sync.CreateSyncFile(dlgSave.FileName, date, new string[] { "Stores", "Companies", "Customers", "Dispensers", "Imports", "Debts", "Sells", "Expenses", "Payments", "Receipts" });
                }
                XtraMessageBox.Show("File báo cáo " + dlgSave.FileName + " đã được tạo thành công.", "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (currentStore != Guid.Empty)
                {
                    sendReport(dlgSave.FileName);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void lvUsers_ItemActivate(object sender, EventArgs e)
        {
            if (lvUsers.SelectedItems.Count > 0)
            {
                RemoveUser(lvUsers.SelectedItems[0].Text);
            }
        }

        private void sendReport(string fileName)
        {
            using (frmMailInfo mailInfo = new frmMailInfo())
            {

                if (mailInfo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    using (FrmSendingMail frm = new FrmSendingMail())
                    {
                        frm.sendReport(fileName, mailInfo.txtSubject.Text, mailInfo.txtBody.Text);
                    }
                }
            }
        }

        private void gridViewPayments_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.IsNewItemRow(e.RowHandle) && e.Column.FieldName == "Customer")
            {
                OilDB.DataSetOilManagement.PaymentsRow newRow = (OilDB.DataSetOilManagement.PaymentsRow)view.GetDataRow(e.RowHandle);
                OilDB.DataSetOilManagement.CustomersRow row = data.DsOil.Customers.FindByID((Guid)newRow["Customer"]);
                if (!(row["Company"] is System.DBNull))
                {
                    newRow["Company"] = row["Company"];
                }
            }

            gridView_CellValueChanged(sender, e);
        }

        private void gridViewReceipts_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.IsNewItemRow(e.RowHandle) && e.Column.FieldName == "Company")
            {
                OilDB.DataSetOilManagement.ReceiptsRow newRow = (OilDB.DataSetOilManagement.ReceiptsRow)view.GetDataRow(e.RowHandle);
                //OilDB.DataSetOilManagement.CustomersRow row = data.DsOil.Customers.FindByID((Guid)newRow["Customer"]);
                //if (!(row["Company"] is System.DBNull))
                //{
                //    newRow["Company"] = row["Company"];
                //}
                //newRow["Company2Address"] = newRow["Company"];
                //newRow["Company2TaxCode"] = newRow["Company"];
            }

            gridView_CellValueChanged(sender, e);
        }

        private void DebtStoreEdit_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Guid store = (Guid)DebtStoreEdit.EditValue;
                data.loadDebtStatisticsAll(store);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DebtComStoreEdit_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Guid store = (Guid)DebtComStoreEdit.EditValue;
                data.loadDebtStatisticsCompany(store);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DateEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                DateTime newVal = e.NewValue == null ? DateTime.Today : (DateTime)e.NewValue;
                DateTime oldVal = e.OldValue == null ? DateTime.Today : (DateTime)e.OldValue;
                TimeSpan range;
                if (newVal > oldVal)
                {
                    range = newVal - oldVal;
                }
                else
                {
                    range = oldVal - newVal;
                }
                if (range.Days > 30)
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Chon ngay loi");
            }
        }

        private void HoaDonKhachHang_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;

            RepositoryItemLookUpEdit Edit;

            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))

                return;



            Row = data.DsOil.Receipts.NewRow();
       

            Row["Company"] = e.DisplayValue;
            Row["ID"] = Guid.NewGuid();
            Row["ReceiptNumber"] = 9999;
            Row["StoreID"] = Guid.NewGuid();
            Row["ReceiptTime"] = DateTime.Today;
            Row["ReceiptNumber"] = 9999;
            Row["CompanyAddress"] = 9999;
            Row["TaxCode"] = 9999;
            Row["Product"] = Guid.NewGuid();
            Row["Price"] = 9999;
            Row["FeePerUnit"] = 9999;
            Row["Amount"] = 9999;

            data.DsOil.Receipts.Rows.Add(Row);

            e.Handled = true;
        }

     
    }
}